#pragma once

#include <iostream>
#include <unordered_map>
#include <fstream>
#include "log.hpp"
#include "InetAddr.hpp"

using namespace MyLog;
const std::string path = "./dict.txt";
const std::string GAP = "：";

class Dict
{
public:
    Dict(const std::string &filepath = path)
        : _filepath(filepath)
    {}

    ~Dict(){}

    void Load()
    {
        // 从执行文件中加载单词表
        std::ifstream in(_filepath);
        if(!in){
            LOG(loglevel::FATAL) << "open file fail";
            return;
        }

        std::string text;
        while(std::getline(in, text)){
            // 分割字符串
            // accurate：准确的，精确的

            auto pos = text.find(GAP);
            if(pos == std::string::npos){
                LOG(loglevel::WARINING) << "data error";
                continue;
            }
            std::string English = text.substr(0, pos);
            std::string Chinese = text.substr(pos + GAP.size());

            if(English.empty() || Chinese.empty()){
                LOG(loglevel::WARINING) << "data loss";
                continue;
            }
            _dict.emplace(English, Chinese);
        }

        in.close();
    }

    // 我们除了对发送的英文进行翻译，还想知道是谁在进行该操作
    std::string Translate(const std::string &word, InetAddr &client)
    {
        auto iter = _dict.find(word);
        if(iter == _dict.end()){
            LOG(loglevel::WARINING) << "Not found->" << word;
            return "None";
        }

        LOG(loglevel::DEBUG) << "[" << client.Ip() <<":" << std::to_string(client.Port()) << "]进入翻译模块# " << word << "->" << iter->second;
        return iter->second;
    }
private:
    std::string _filepath; // 从指定路径下的指定文件中加载单词表
    std::unordered_map<std::string, std::string> _dict;
};